import {
    Button,
    Cascader,
    Col,
    Flex,
    Form,
    Input,
    message,
    Modal,
    Radio,
    Row,
    Select,
    Space,
    Table,
    TreeSelect,
    Typography
} from 'antd'
import React from 'react'
import {useState, useEffect} from 'react'
import {useParams, useNavigate} from 'react-router-dom'
import Amap from '../components/Amap'
import ImageUpload from '../components/ImageUpload'
import ManyUpload from '../components/ManyUpload'
import {adminActivatyInfo, adminActivatyList} from '../service/activaty'
import {
    categoryList,
    contentArticleAdd,
    contentArticleDetail,
    contentArticleEdit
} from '../service/content'
import {cityTreeAPI, shopDetail, shopList, shopListByCityIdAPI} from '../service/shop'
import {contentTagList, tagList} from '../service/tag'
import {getStorage} from '../utils/tools'
import SimpleEditor from "../utils/SimpleEditor";
import RichTextEditor from "../utils/RichTextEditor";

function ContentAdd() {
    const navigate = useNavigate()
    const {id} = useParams() // 获取路由参数中的id
    const [digestContent, setDigestContent] = useState('');
    const [content, setContent] = useState('');
    const isEditing = id !== undefined // 根据id是否存在判断是编辑还是添加
    // 选择指定区域
    const [region, setRegion] = useState([])
    // 三级省市区数据
    const [regionData, setRegionData] = useState([])
    // 临时保存门店
    const [tmpShopId, setTmpShopId] = useState()
    // 保存页码
    const [pageNo, setPageNo] = useState(1)
    // 总数据量
    const [total, setTotal] = useState(0)
    // 搜索条件
    const [condition, setCondition] = useState({})
    const [shopName, setShopName] = useState('请选择')
    const [shopId, setShopId] = useState()
    // 临时保存店铺
    const [tmpShopName, setTmpShopName] = useState('')
    // 临时保存ID
    const [lbsShopList, setLbsShopList] = useState([])
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [isModalOpen2, setIsModalOpen2] = useState(false)
    // 创建表单的引用
    const [form] = Form.useForm()
    // 保存门店照片
    const [fileList, setFileList] = useState([])
    const [position, setPosition] = useState({
        longitude: 116.397428,
        latitude: 39.90923
    })
    const [imageCover, setImageCover] = useState()
    const [n, setN] = useState(0)
    // 文章分类列表
    const [cateList, setCateList] = useState([])
    // 标签列表
    const [list, setList] = useState([])
    // 选中的标签列表
    const [selectedList, setSelectedList] = useState([])
    const requestShop = async () => {
        const res = await shopList({
            ...condition,
            pageNo,
            pageSize: 10
        })
        console.log(res)
        if (res.data) {
            setLbsShopList(res.data.objects)
            setTotal(res.data.total)
        }
    }
    // 保存页码
    const [pageNo2, setPageNo2] = useState(1)
    // 提交表单类型
    const [submitType, setSubmitType] = useState('')
    // 搜索条件
    const [condition2, setCondition2] = useState({})
    // 选择活动
    const [tmpActivatyId, setTmpActivatyId] = useState()
    const [ActivatyId, setActivatyId] = useState()
    const [tmpActivatyName, setTmpActivatyName] = useState()
    const [ActivatyName, setActivatyName] = useState('请选择')
    const [activatyList, setActivatyList] = useState([])
    // 活动列表
    const requestActivaty = async () => {
        const res = await adminActivatyList({
            ...condition2,
            pageNo: pageNo2,
            pageSize: 10
        })
        console.log(res)
        // setTotal2(res.data.total)
        if (res.data) {
            setActivatyList(res.data.objects)
        }
    }

    // 递归函数处理三级城市树
    function transformData(data) {
        return data.map((item) => {
            return {
                ...item,
                label: item.name,
                value: item.id,
                children: item.children ? transformData(item.children) : null
            }
        })
    }

    // 递归获取节点层级
    const getNodeLevel = (value, data) => {
        for (const item of data) {
            if (item.value === value[0]) {
                return item.depth;
            }
            if (item.children && item.children.length) {
                const level = getNodeLevel(value, item.children);
                if (level) return level;
            }
        }
        return null;
    };
    // 提交表单
    const onFinish = async (v) => {
        const pics = fileList.map((item) => {
            if (item.response) {
                return item.response.data.url
            } else {
                return item.url
            }
            v.articleDetail = content;
            v.articleDigest = digestContent;
        })
        v.articleCover = imageCover
        // 处理标签数组
        let arr = selectedList.map(subArray => {
            // 如果子数组只有一个元素，则返回该元素
            // 如果子数组有两个元素，则返回第二个元素
            return subArray.length === 1 ? subArray[0] : subArray[1]
        })
        console.log(arr)
        // 处理标签
        v.articleLabel = arr.join(',')
        // 处理图片
        v.articlePic = pics.join(',')
        // 处理经纬度
        v.latitude = v.zuobiao.split(',')[0]
        v.longitude = v.zuobiao.split(',')[1]
        delete v.zuobiao
        v.shopId = shopId
        // 活动ID
        v.activityId = ActivatyId
        v.userId = getStorage('userId')
        // 如果是直接提交，状态-1 ，草稿箱-2
        if (submitType === 'submit') {
            // 处理正式提交的逻辑
            v.articleStatus = 1
        } else if (submitType === 'draft') {
            // 处理保存草稿的逻辑
            v.articleStatus = 0
        }
        console.log(v)
        // 如果不是编辑
        if (!isEditing) {
            v.accessCount = 1
            v.likeCount = 1
            const res = await contentArticleAdd(v)
            console.log(res)
            if (res.code === '0') {
                message.success('添加成功')
                setTimeout(() => {
                    navigate('/admin/content/twitter')
                }, 1000)
            } else {
                message.error('添加失败')
            }
        } else {
            v.id = id
            const res = await contentArticleEdit(v)
            console.log(res)
            if (res.code === '0') {
                message.success('编辑成功')
                setTimeout(() => {
                    navigate('/admin/content/twitter')
                }, 1000)
            } else {
                message.error('编辑失败')
            }
        }
    }
    // 设置按钮点击
    const handleButtonClick = (type) => {
        setSubmitType(type)
        form.submit()
    }
    useEffect(() => {
        // 获取三级城市树
        ;(async () => {
            const res = await cityTreeAPI()
            console.log(res.data)
            const newData = transformData(res.data)
            console.log(newData)
            setRegionData(newData)
        })()
        ;(async () => {
            // 获取分类
            const res2 = await categoryList()
            console.log(res2)
            setCateList(res2.data.objects)
            // 获取标签分类
            const res1 = await contentTagList()
            console.log(res1)
            const arr = []
            for (let key in res1.data) {
                const arr2 = res1.data[key].map((item) => {
                    return {
                        label: item.tagLibraryBO.tagName,
                        value: item.tagLibraryBO.tagName
                        // value: item.tagLibraryBO.id
                    }
                })
                arr.push({
                    label: key,
                    value: key,
                    children: arr2
                })
            }
            // console.log('数组', arr)
            setList(arr)
        })()
        // 判断是否为编辑
        if (isEditing) {
            // 获取文章详情
            ;(async () => {
                const res = await contentArticleDetail({
                    id
                })
                console.log(res)
                form.setFieldsValue({
                    ...res.data
                })
                // 设置封面图
                setImageCover(res.data.articleCover)
                // 设置文章主图片
                setFileList(
                    res.data.articlePic.split(',').map((item) => ({url: item}))
                )
                console.log(res.data.articleLabel)
                setDigestContent(res.data.articleDigest);
                // 设置标签，每个标签放入二维数组
                const arr = res.data.articleLabel.split(',')
                // 将数组转为二维数组
                const arr2 = arr.map((item) => {
                    return [item]
                })
                console.log(arr2)
                setSelectedList(arr)
                // 设置坐标
                setPosition({
                    longitude: res.data.longitude,
                    latitude: res.data.latitude
                })
                // 设置店铺ID
                setShopId(res.data.shopId)
                // 通过店铺id查询店铺名称
                ;await (async () => {
                    const res2 = await shopDetail(res.data.shopId)
                    console.log(res2)
                    if (res2.data) {
                        setShopName(res2.data.storeName)
                        setShopId(res.data.shopId)
                    }
                })()
                // 设置活动Id
                setActivatyId(res.data.activityId)
                // 通过活动id查询活动名称
                ;await (async () => {
                    const res2 = await adminActivatyInfo(res.data.activityId)
                    console.log(res2)
                    if (res2.data) {
                        setActivatyName(res2.data.activityName)
                        setActivatyId(res.data.activityId)
                    }
                })()
            })()
        }
    }, [])
    useEffect(() => {
        form.setFieldsValue({
            zuobiao: `${position.latitude},${position.longitude}`
        })
    }, [position.longitude])
    return (
        <>
            <Row className="info">
                <Col span={24}>
                    <Flex justify={'space-between'}>
                        <Typography.Title level={3}>内容管理</Typography.Title>
                    </Flex>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Typography.Title level={4}>
                        {isEditing ? '编辑推文' : '推文创作'}
                    </Typography.Title>
                </Col>
                <Col span={24} style={{width: '100%'}}>
                    <Form
                        form={form}
                        labelCol={{
                            span: 3
                        }}
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="文章标题："
                            name="articleTitle"
                            rules={[
                                {
                                    required: true,
                                    message: '标题不能为空'
                                }
                            ]}
                        >
                            <Input style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item
                            label="文章分类："
                            name="articleCategoryId"
                            rules={[
                                {
                                    required: true,
                                    message: '分类不能为空'
                                }
                            ]}
                        >
                            <Select
                                style={{width: 400}}
                                options={cateList}
                                fieldNames={{label: 'categoryName', value: 'id'}}
                            />
                        </Form.Item>
                        <Form.Item
                            label="文章标签："
                            name="articleLabel"
                            rules={[
                                {
                                    required: true,
                                    message: '标签不能为空'
                                }
                            ]}
                        >
                            <Cascader
                                // 设置默认值
                                defaultValue={selectedList}
                                style={{width: 400}}
                                options={list}
                                multiple
                                onChange={(value) => {
                                    console.log(value)
                                    setSelectedList(value)
                                }}
                            />
                        </Form.Item>
                        <Form.Item
                            label="文章摘要："
                            name="articleDigest"
                            rules={[
                                {
                                    required: true,
                                    message: '文章摘要不能为空'
                                }
                            ]}
                        >
                            <SimpleEditor
                                initialContent={digestContent}
                                onChange={setDigestContent}
                            />
                        </Form.Item>
                        <Form.Item label="文章封面：" name="articleCover">
                            <ImageUpload imageUrl={imageCover} setImageUrl={setImageCover}/>
                        </Form.Item>
                        <Form.Item label="主图图片：" name="articlePic">
                            <ManyUpload fileList={fileList} setFileList={setFileList}/>
                        </Form.Item>
                        <Form.Item
                            label="文章详情："
                            name="articleDetail"
                            rules={[
                                {
                                    required: true,
                                    message: '文章详情不能为空'
                                }
                            ]}
                        >
                            <RichTextEditor
                                value={content}
                                onChange={setContent}
                                width="85%"
                            />
                        </Form.Item>
                        <Form.Item label="选择店铺：" name="shopId">
                            <div
                                style={{
                                    width: 400,
                                    height: 34,
                                    padding: 5,
                                    border: '1px solid #D9D9D9',
                                    borderRadius: 5
                                }}
                                onClick={async (e) => {
                                    await requestShop()
                                    setIsModalOpen(true)
                                }}
                            >
                                {shopName}
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="活动引流标语："
                            name="activityWord"
                            rules={[
                                {
                                    required: true,
                                    message: '引流标语不能为空'
                                }
                            ]}
                        >
                            <Input style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item label="选择活动：">
                            <div
                                style={{
                                    width: 400,
                                    height: 34,
                                    padding: 5,
                                    border: '1px solid #D9D9D9',
                                    borderRadius: 5
                                }}
                                onClick={async (e) => {
                                    await requestActivaty()
                                    setIsModalOpen2(true)
                                }}
                            >
                                {ActivatyName}
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="文章定位"
                            name="zuobiao"
                            rules={[{required: true, message: '请输入营业时间'}]}
                        >
                            <Input readOnly style={{width: 400}}/>
                        </Form.Item>
                        <Form.Item label=" " colon={false}>
                            <Amap
                                width="800"
                                height="200"
                                position={position}
                                setPosition={setPosition}
                            />
                        </Form.Item>
                        <Form.Item label=" " colon={false}>
                            <Row>
                                <Col span={2}>
                                    <Form.Item label=" " colon={false}>
                                        <Button
                                            // htmlType="submit"
                                            type="primary"
                                            onClick={() => handleButtonClick('submit')}
                                        >
                                            提交
                                        </Button>
                                    </Form.Item>
                                </Col>
                                <Col span={2}>
                                    <Form.Item label=" " colon={false}>
                                        <Button
                                            // htmlType="submit"
                                            onClick={() => handleButtonClick('draft')}
                                        >
                                            保存草稿
                                        </Button>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
            {/* 选择店铺模态框 */}
            <Modal
                title="选择店铺"
                open={isModalOpen}
                onOk={() => {
                    setShopId(tmpShopId)
                    setShopName(tmpShopName)
                    setIsModalOpen(false)
                }}
                onCancel={() => {
                    setIsModalOpen(false)
                }}
                maskClosable={false}
                width={800}
                destroyOnClose
            >
                <Form
                    layout="inline"
                    onFinish={async (v) => {
                        // console.log(v)
                        // setPageNo(1)
                        // setCondition({ ...v })
                        // await requestShop()
                        // setN(n + 1)
                    }}
                >
                    <Form.Item name="storeName">
                        <Input placeholder="请输入店铺名称"/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
                <Row>
                    <Col span={8} style={{paddingTop: 20, paddingRight: 20}}>
                        <TreeSelect
                            style={{width: '100%'}}
                            placeholder="区域选择"
                            treeData={regionData}
                            value={region}
                            treeCheckable={true}
                            onChange={async (value) => {
                                setRegion(value)
                                console.log(value)
                                const level = getNodeLevel(value, regionData);
                                // 如果数组不为空
                                if (value.length !== 0) {
                                    // 查询对应的店铺
                                    const res = await shopListByCityIdAPI({
                                        level: level,
                                        cityIdList: value,
                                        pageNo: 1,
                                        pageSize: 100
                                    })
                                    console.log(res)

                                    if (res.data) {
                                        setLbsShopList(res.data.objects || res.data)
                                    }
                                } else {
                                    setLbsShopList([]);
                                }
                            }}
                            showCheckedStrategy={TreeSelect.SHOW_PARENT}
                        />
                    </Col>
                    <Col span={16}>
                        <Space direction="vertical" size="middle" style={{width: '100%'}}>
                            <Table
                                rowKey={(record) => record.id}
                                // 设置默认选中的
                                selectedRowKeys={tmpShopId}
                                rowSelection={{
                                    type: 'radio',
                                    // 获取选中的
                                    onChange: (selectedRowKeys, selectedRows) => {
                                        console.log(selectedRowKeys, selectedRows)
                                        setTmpShopName(selectedRows[0].storeName)
                                        setTmpShopId(selectedRowKeys[0])
                                    }
                                }}
                                pagination={{
                                    total,
                                    defaultCurrent: 1,
                                    onChange: async (page) => {
                                        setPageNo(page)
                                        await requestShop()
                                    }
                                }}
                                dataSource={lbsShopList}
                                columns={[
                                    {
                                        title: '编号',
                                        dataIndex: 'id',
                                        key: 'id'
                                    },
                                    {
                                        title: '门店名称',
                                        dataIndex: 'storeName',
                                        key: 'storeName'
                                    }
                                ]}
                            />
                        </Space>
                    </Col>
                </Row>

            </Modal>

            {/* 选择活动 */}
            <Modal
                title="选择活动"
                open={isModalOpen2}
                onOk={() => {
                    setActivatyId(tmpActivatyId)
                    setActivatyName(tmpActivatyName)
                    setIsModalOpen2(false)
                }}
                onCancel={() => {
                    setIsModalOpen2(false)
                }}
                maskClosable={false}
                width={800}
                // destroyOnClose
            >
                <Space direction="vertical" size="middle" style={{width: '100%'}}>
                    <Radio.Group
                        onChange={(e) => {
                            console.log(e)
                            const arr = e.target.value.split(',')
                            setTmpActivatyId(arr[0])
                            setTmpActivatyName(arr[1])
                        }}
                        style={{width: '100%'}}
                    >
                        <Table
                            pagination={{
                                total,
                                defaultCurrent: 1,
                                onChange: async (page) => {
                                    setPageNo2(page)
                                    await requestActivaty()
                                }
                            }}
                            // 设置key
                            key="id"
                            dataSource={activatyList}
                            columns={[
                                {
                                    title: '编号',
                                    dataIndex: 'id',
                                    key: 'id'
                                },
                                {
                                    title: '活动名称',
                                    dataIndex: 'activityName',
                                    key: 'activityName'
                                },
                                {
                                    title: '活动目标',
                                    dataIndex: 'activityTarget',
                                    key: 'activityTarget'
                                },
                                {
                                    title: '活动类型',
                                    dataIndex: 'activityType',
                                    key: 'activityType',
                                    render: (_, record) => {
                                        return <span>赠领</span>
                                    }
                                },
                                {
                                    title: '投放渠道',
                                    dataIndex: 'deliveryChannel',
                                    key: 'deliveryChannel',
                                    render: (_, record) => {
                                        return (
                                            <span>
                        {record.deliveryChannel === 1 && '内容页面'}
                                                {record.deliveryChannel === 2 && '定时推送'}
                                                {record.deliveryChannel === 3 && '即时推送'}
                      </span>
                                        )
                                    }
                                },
                                {
                                    title: '营销方式',
                                    dataIndex: 'rewardType',
                                    key: 'rewardType',
                                    render: (_, record) => {
                                        return <>优惠券</>
                                    }
                                },
                                {
                                    title: '活动时间',
                                    dataIndex: 'startDate',
                                    key: 'startDate'
                                },
                                {
                                    title: '操作',
                                    dataIndex: 'op',
                                    key: 'op',
                                    render: (_, record) => {
                                        return (
                                            <Radio value={record.id + ',' + record.activityName}/>
                                        )
                                    }
                                }
                            ]}
                        />
                    </Radio.Group>
                </Space>
            </Modal>
        </>
    )
}

export default ContentAdd
